<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <router-link to="/index">
            <i class="el-icon-s-home"></i> 首页
          </router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>救援服务</el-breadcrumb-item>
        <el-breadcrumb-item>小修价格</el-breadcrumb-item>
        <el-breadcrumb-item>价格计算工具</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; font-size: 16px;">小修价格计算工具</span>
      </div>
      
      <!-- 单个价格计算 -->
      <el-form :model="singleForm" ref="singleForm" label-width="120px" class="demo-form-inline">
        <el-form-item label="小修类型" prop="repairType">
          <el-select v-model="singleForm.repairType" placeholder="请选择小修类型" style="width: 200px">
            <el-option
              v-for="type in repairTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车型ID" prop="modelId">
          <el-input v-model="singleForm.modelId" placeholder="请输入车型ID" style="width: 200px" />
        </el-form-item>
        <el-form-item label="实际里程" prop="mileage">
          <el-input v-model="singleForm.mileage" placeholder="请输入实际里程" style="width: 200px">
            <template slot="append">km</template>
          </el-input>
        </el-form-item>
        <el-form-item label="服务商ID" prop="serviceId">
          <el-input v-model="singleForm.serviceId" placeholder="请输入服务商ID（可选）" style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="calculateSinglePrice" :loading="singleLoading">
            <i class="el-icon-money"></i> 计算价格
          </el-button>
          <el-button @click="resetSingleForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 单个价格计算结果 -->
    <el-card class="box-card" v-if="singleResult">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; font-size: 16px;">价格计算结果</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="小修类型">{{ singleResult.repairTypeName }}</el-descriptions-item>
            <el-descriptions-item label="车型ID">{{ singleResult.modelId }}</el-descriptions-item>
            <el-descriptions-item label="实际里程">{{ singleResult.mileage }}km</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="客户价格">
              <span style="color: #E6A23C; font-weight: bold; font-size: 18px;">{{ singleResult.customerPrice }}元</span>
            </el-descriptions-item>
            <el-descriptions-item label="服务商价格">
              <span style="color: #67C23A; font-weight: bold; font-size: 16px;">{{ singleResult.serviceProviderPrice }}元</span>
            </el-descriptions-item>
            <el-descriptions-item label="司机价格">
              <span style="color: #409EFF; font-weight: bold; font-size: 16px;">{{ singleResult.driverPrice }}元</span>
            </el-descriptions-item>
            <el-descriptions-item label="代理下单价格">
              <span style="color: #909399; font-weight: bold; font-size: 16px;">{{ singleResult.agentOrderPrice }}元</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      
      <!-- 价格计算详情 -->
      <el-divider content-position="left">价格计算详情</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header">客户价格计算</div>
            <p>{{ singleResult.customerPriceDesc }}</p>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header">服务商价格计算</div>
            <p>{{ singleResult.serviceProviderPriceDesc }}</p>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header">司机价格计算</div>
            <p>{{ singleResult.driverPriceDesc }}</p>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header">代理下单价格计算</div>
            <p>{{ singleResult.agentOrderPriceDesc }}</p>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 批量价格计算 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; font-size: 16px;">批量价格计算</span>
      </div>
      
      <el-form :model="batchForm" ref="batchForm" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="小修类型" prop="repairType">
              <el-select v-model="batchForm.repairType" placeholder="请选择小修类型" style="width: 100%">
                <el-option
                  v-for="type in repairTypeOptions"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车型ID" prop="modelId">
              <el-input v-model="batchForm.modelId" placeholder="请输入车型ID" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="calculateBatchPrice" :loading="batchLoading">
                <i class="el-icon-s-data"></i> 批量计算
              </el-button>
              <el-button @click="resetBatchForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="里程列表">
          <el-input
            type="textarea"
            v-model="mileagesText"
            placeholder="请输入里程，用逗号分隔，例如：5,10,15,20,25"
            :rows="3"
            style="width: 100%"
          />
          <div style="margin-top: 10px;">
            <el-button size="small" @click="addPresetMileages('common')">常用里程</el-button>
            <el-button size="small" @click="addPresetMileages('range')">范围里程</el-button>
            <el-button size="small" @click="clearMileages">清空</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 批量计算结果 -->
    <el-card class="box-card" v-if="batchResults && batchResults.length > 0" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; font-size: 16px;">批量计算结果</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="exportBatchResults">导出结果</el-button>
      </div>
      
      <el-table :data="batchResults" border style="width: 100%">
        <el-table-column prop="mileage" label="里程(km)" align="center" width="100" />
        <el-table-column prop="customerPrice" label="客户价格(元)" align="center" width="120">
          <template slot-scope="scope">
            <span style="color: #E6A23C; font-weight: bold;">{{ scope.row.customerPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="serviceProviderPrice" label="服务商价格(元)" align="center" width="140">
          <template slot-scope="scope">
            <span style="color: #67C23A; font-weight: bold;">{{ scope.row.serviceProviderPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="driverPrice" label="司机价格(元)" align="center" width="120">
          <template slot-scope="scope">
            <span style="color: #409EFF; font-weight: bold;">{{ scope.row.driverPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="agentOrderPrice" label="代理下单价格(元)" align="center" width="140">
          <template slot-scope="scope">
            <span style="color: #909399; font-weight: bold;">{{ scope.row.agentOrderPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="价格说明" prop="customerPriceDesc" min-width="300" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {
  calculatePrice,
  calculateDriverPrice,
  getRepairTypes,
  batchCalculatePrice
} from '@/api/repair/priceCalculator'

export default {
  name: 'PriceCalculator',
  data() {
    return {
      // 小修类型选项
      repairTypeOptions: [],
      // 单个计算表单
      singleForm: {
        repairType: '',
        modelId: '',
        mileage: '',
        serviceId: ''
      },
      // 单个计算结果
      singleResult: null,
      // 单个计算加载状态
      singleLoading: false,
      // 批量计算表单
      batchForm: {
        repairType: '',
        modelId: ''
      },
      // 里程文本
      mileagesText: '',
      // 批量计算结果
      batchResults: [],
      // 批量计算加载状态
      batchLoading: false
    }
  },
  created() {
    this.getRepairTypeOptions()
  },
  methods: {
    /** 获取小修类型选项 */
    getRepairTypeOptions() {
      getRepairTypes().then(response => {
        this.repairTypeOptions = response.data
      })
    },
    /** 计算单个价格 */
    calculateSinglePrice() {
      if (!this.singleForm.repairType || !this.singleForm.modelId || !this.singleForm.mileage) {
        this.$modal.msgError('请填写完整的计算参数')
        return
      }
      
      this.singleLoading = true
      const params = {
        repairType: this.singleForm.repairType,
        modelId: this.singleForm.modelId,
        mileage: this.singleForm.mileage
      }
      
      // 如果有服务商ID，则计算司机价格
      if (this.singleForm.serviceId) {
        params.serviceId = this.singleForm.serviceId
        calculateDriverPrice(params).then(response => {
          this.singleResult = response.data
          this.singleLoading = false
        }).catch(() => {
          this.singleLoading = false
        })
      } else {
        calculatePrice(params).then(response => {
          this.singleResult = response.data
          this.singleLoading = false
        }).catch(() => {
          this.singleLoading = false
        })
      }
    },
    /** 重置单个计算表单 */
    resetSingleForm() {
      this.singleForm = {
        repairType: '',
        modelId: '',
        mileage: '',
        serviceId: ''
      }
      this.singleResult = null
    },
    /** 计算批量价格 */
    calculateBatchPrice() {
      if (!this.batchForm.repairType || !this.batchForm.modelId || !this.mileagesText.trim()) {
        this.$modal.msgError('请填写完整的计算参数')
        return
      }
      
      // 解析里程列表
      const mileages = this.mileagesText.split(',').map(item => {
        const num = parseFloat(item.trim())
        return isNaN(num) ? null : num
      }).filter(item => item !== null)
      
      if (mileages.length === 0) {
        this.$modal.msgError('请输入有效的里程数据')
        return
      }
      
      this.batchLoading = true
      const data = {
        repairType: this.batchForm.repairType,
        modelId: this.batchForm.modelId,
        mileages: mileages
      }
      
      batchCalculatePrice(data).then(response => {
        this.batchResults = response.data
        this.batchLoading = false
      }).catch(() => {
        this.batchLoading = false
      })
    },
    /** 重置批量计算表单 */
    resetBatchForm() {
      this.batchForm = {
        repairType: '',
        modelId: ''
      }
      this.mileagesText = ''
      this.batchResults = []
    },
    /** 添加预设里程 */
    addPresetMileages(type) {
      if (type === 'common') {
        this.mileagesText = '5,10,15,20,25,30,35,40,45,50'
      } else if (type === 'range') {
        this.mileagesText = '10,20,30,40,50,60,70,80,90,100,150,200'
      }
    },
    /** 清空里程 */
    clearMileages() {
      this.mileagesText = ''
      this.batchResults = []
    },
    /** 导出批量结果 */
    exportBatchResults() {
      if (this.batchResults.length === 0) {
        this.$modal.msgError('没有可导出的数据')
        return
      }
      
      // 创建CSV内容
      const headers = ['里程(km)', '客户价格(元)', '服务商价格(元)', '司机价格(元)', '代理下单价格(元)', '价格说明']
      const csvContent = [
        headers.join(','),
        ...this.batchResults.map(row => [
          row.mileage,
          row.customerPrice,
          row.serviceProviderPrice,
          row.driverPrice,
          row.agentOrderPrice,
          `"${row.customerPriceDesc}"`
        ].join(','))
      ].join('\n')
      
      // 下载文件
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob)
        link.setAttribute('href', url)
        link.setAttribute('download', `小修价格批量计算结果_${new Date().getTime()}.csv`)
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    }
  }
}
</script>

<style scoped>
.breadcrumb-container {
  padding: 10px 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
}

.breadcrumb-container .el-breadcrumb {
  font-size: 14px;
}

.breadcrumb-container i {
  margin-right: 5px;
  color: #409eff;
}

.box-card {
  margin-bottom: 20px;
}

.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.demo-form-inline .el-form-item {
  margin-right: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
